from ..extensions.extensions import db
from flask import current_app
import sqlite3
import os

def init_database():
    """初始化数据库"""
    try:
        # 获取数据库文件路径
        db_path = current_app.config['SQLALCHEMY_DATABASE_URI'].replace('sqlite:///', '')
        
        # 如果数据库文件不存在，则创建表并导入测试数据
        if not os.path.exists(db_path):
            # 创建数据库表
            #db.create_all()
            
            # 执行SQL脚本导入测试数据
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            
            # 读取SQL文件
            sql_files = [
                'users.sql',
                'roles.sql',
                'permissions.sql',
                'user_roles.sql',
                'role_permissions.sql',
                'demo_data.sql'
            ]
            
            for sql_file in sql_files:
                with open(f'{sql_file}', 'r', encoding='utf-8') as f:
                    sql_script = f.read()
                    # 分割SQL语句并执行
                    for statement in sql_script.split(';'):
                        if statement.strip():
                            cursor.execute(statement)
            
            conn.commit()
            conn.close()
            
            current_app.logger.info('Database initialized successfully')
    except Exception as e:
        current_app.logger.error(f'Database initialization failed: {str(e)}')
        raise e 